package com.glela.goods.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.glela.common.util.DateUtil;
import com.glela.common.util.StringUtil;
import com.glela.goods.mapper.BrandHotMapper;
import com.glela.goods.mapper.CategoryMapper;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.GoodsNavigateMapper;
import com.glela.goods.model.BrandHot;
import com.glela.goods.model.Category;
import com.glela.goods.model.Goods;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.GoodsPrice;
import com.glela.goods.model.StoreGoods;
import com.glela.goods.model.vo.CategoryVo;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.service.CategoryService;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.InventoryService;
import com.glela.goods.service.StoreGoodsService;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponsePageModel;

@Service("categoryService")
@Scope("singleton")
public class CategoryServiceImpl implements CategoryService {

	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private BrandHotMapper brandHotMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private GoodsNavigateMapper goodsNavigateMapper;
	@Autowired
	private StoreGoodsService storeGoodsService;
	
	

//	@Override
//	public ResponsePageModel<CategoryVo> listCategory() {
//		//获取所有的父类
//		List<Category> list = categoryMapper.selectCategoryParent();
//		List<CategoryVo> listvo = new ArrayList<CategoryVo>();
//		//循环父类提取每个父类下的子类
//		for (int i = 0; i < list.size(); i++) {
//			Category category = list.get(i);
//			int parentId = category.getId() ;
//			CategoryVo vo = new CategoryVo(category) ;
//			//查询子类对象
//			List<Category> sublist = categoryMapper.selectCategory(parentId);
//			List<CategoryVo> sublistvo = new ArrayList<CategoryVo>();
//			//子类vo对象转换
//			for (Category c : sublist) {
//				sublistvo.add(new CategoryVo(c));
//			}
//			//子类对象添加到父类中
//			vo.setCategoryVolist(sublistvo);
//			//返回父类加入数组
//			listvo.add(vo);
//		}
//		return new ResponsePageModel<CategoryVo>(listvo.size(), listvo.size(), 1, listvo);
//	}
	
	/**
	 * 商品分类有二级改为三级，适用老版本，修改老版本分类列表实现
	 */
	@Override
	public ResponsePageModel<CategoryVo> listCategory() {
		/*List<CategoryVo> result = new ArrayList<CategoryVo>();
		// 一级分类列表
		List<Category> firstCategoryList = this.categoryMapper.selectCategoryParent();
		if (!CollectionUtils.isEmpty(firstCategoryList)) {
			for (Category firstCategory : firstCategoryList) {
				CategoryVo firstVo = new CategoryVo(firstCategory);
				// 二级分类列表
				List<Category> secondCategoryList = this.categoryMapper.selectCategory(firstCategory.getId());
				if (!CollectionUtils.isEmpty(secondCategoryList)) {
					for (Category secondCategory : secondCategoryList) {
						List<Category> thirdCategoryList = this.categoryMapper.selectThirdCategoryByParentIdAndIsShow(secondCategory.getId(),2);
						if (!CollectionUtils.isEmpty(thirdCategoryList)) {
//							CategoryVo vo = new CategoryVo(secondCategory);
							List<CategoryVo> categoryVolist = new ArrayList<CategoryVo>();
							for (Category thirdCategory : thirdCategoryList) {
								categoryVolist.add(new CategoryVo(thirdCategory));
							}
							*//*if (StringUtils.isNotBlank(newFlag)){
								//子类对象添加到父类中
								vo.setCategoryVolist(categoryVolist);
								//返回父类加入数组
								result.add(vo);
							}else{*//*
								//子类对象添加到父类中
							firstVo.setCategoryVolist(categoryVolist);
							//返回父类加入数组
							result.add(firstVo);
//							}
						}
					}
				}
			}
		}
		return new ResponsePageModel<CategoryVo>(result.size(), result.size(), 1, result);*/
		//获取所有的父类
		List<Category> list = categoryMapper.selectCategoryParent();
		List<CategoryVo> listvo = new ArrayList<CategoryVo>();
		//循环父类提取每个父类下的子类
		for (int i = 0; i < list.size(); i++) {
			Category category = list.get(i);
			int parentId = category.getId() ;
			CategoryVo vo = new CategoryVo(category) ;
			//查询子类对象
			List<Category> sublist = categoryMapper.selectCategory(parentId);
			List<CategoryVo> sublistvo = new ArrayList<CategoryVo>();
			//子类vo对象转换
			for (Category c : sublist) {
				sublistvo.add(new CategoryVo(c));
			}
			//子类对象添加到父类中
			vo.setCategoryVolist(sublistvo);
			//返回父类加入数组
			listvo.add(vo);
		}
		return new ResponsePageModel<CategoryVo>(listvo.size(), listvo.size(), 1, listvo);
	}

	@Override
	public CategoryVo getCategoryById(int id) {
		// TODO 自动生成的方法存根
		Category category = categoryMapper.selectCategoryById(id);
		if (category == null) {
			return null ;
		}
		CategoryVo vo = new CategoryVo(category);
		return vo;
	}
	
	/**
	 * 查询商品分类列表
	 * 如当前三级分类没有商品，则不显示三级分类
	 * 如二级分类下所有三级分类都没有商品，则不显示二级分类
	 * 如一级分类下的二级分类都不显示，则不显示一级分类和对应的热门品牌
	 */
	@Override
	public List<Map<String, Object>> goodsClassifyList() {
		List<Map<String, Object>> goodsClassifyList = new ArrayList<Map<String,Object>>();
		// 一级分类列表
		List<Category> firstCategoryList = this.categoryMapper.selectCategoryParent();
		if (!CollectionUtils.isEmpty(firstCategoryList)) {
			for (Category firstCategory : firstCategoryList) {
				Map<String, Object> fistClassifyMap = new HashMap<String, Object>();
				// 二级分类列表
				List<Category> secondCategoryList = this.categoryMapper.selectThirdCategoryByParentIdAndIsShow(firstCategory.getId(),2);
				List<Map<String, Object>> secondClassifyList = new ArrayList<Map<String,Object>>();
				Map<String, Object> copy_fristClassifyMap = new HashMap<String, Object>();
				if (!CollectionUtils.isEmpty(secondCategoryList)) {
					for (Category secondCateGory: secondCategoryList) {
						Map<String, Object> secondClassifyMap = new HashMap<String, Object>();
						secondClassifyMap.put("id", secondCateGory.getId());
						secondClassifyMap.put("name", secondCateGory.getName());
						secondClassifyMap.put("icoPath", secondCateGory.getIcoPath());
						secondClassifyList.add(secondClassifyMap);
					}
					List<Map<String, Object>> copy_fristClassifyList = new ArrayList<Map<String,Object>>();
					copy_fristClassifyMap.put("id", firstCategory.getId());
					copy_fristClassifyMap.put("name", firstCategory.getName());
					copy_fristClassifyMap.put("icoPath", firstCategory.getIcoPath());
					copy_fristClassifyMap.put("junior",secondClassifyList);
					copy_fristClassifyList.add(copy_fristClassifyMap);

					fistClassifyMap.put("id", firstCategory.getId());
					fistClassifyMap.put("name", firstCategory.getName());
					fistClassifyMap.put("icoPath", firstCategory.getIcoPath());
					fistClassifyMap.put("junior", copy_fristClassifyList);
					List<BrandHot> hotBrandList = this.brandHotMapper.selectHotBrandsByCateId(firstCategory.getId());
					List<Map<String, Object>> hotBrandMapList = new ArrayList<Map<String,Object>>();
					if (!CollectionUtils.isEmpty(hotBrandList)) {
						for (BrandHot hotBrand : hotBrandList) {
							Map<String, Object> hotBrandMap = new HashMap<String, Object>();
							hotBrandMap.put("id", hotBrand.getBrandId());
							hotBrandMap.put("brand_name", hotBrand.getBrandName());
							hotBrandMap.put("logo_path", hotBrand.getLogoPath());
							hotBrandMapList.add(hotBrandMap);
						}
					}
					fistClassifyMap.put("hotBranchs", hotBrandMapList);
					goodsClassifyList.add(fistClassifyMap);
				}

				/*if (!CollectionUtils.isEmpty(secondCategoryList)) {
					boolean ishasThirdClassify = false;// 是否存在三级分类
					for (Category secondCategory : secondCategoryList) {
						Map<String, Object> secondClassifyMap = new HashMap<String, Object>();
						// 三级分类列表
						List<Category> thirdCategoryList = this.categoryMapper.selectThirdCategoryByParentIdAndIsShow(secondCategory.getId(),1);
						List<Map<String, Object>> thirdClassifyList = new ArrayList<Map<String,Object>>();
						if (!CollectionUtils.isEmpty(thirdCategoryList)) {
							ishasThirdClassify = true;
							for (Category thirdCategory : thirdCategoryList) {
								Map<String, Object> thirdClassifyMap = new HashMap<String, Object>();
								thirdClassifyMap.put("id", thirdCategory.getId());
								thirdClassifyMap.put("name", thirdCategory.getName());
								thirdClassifyMap.put("icoPath", thirdCategory.getIcoPath());
								thirdClassifyList.add(thirdClassifyMap);
							}
							secondClassifyMap.put("id", secondCategory.getId());
							secondClassifyMap.put("name", secondCategory.getName());
							secondClassifyMap.put("icoPath", secondCategory.getIcoPath());
							secondClassifyMap.put("junior", thirdClassifyList);
							secondClassifyList.add(secondClassifyMap);
						}
					}
					// 存在三级商品分类
					if (ishasThirdClassify) {
						fistClassifyMap.put("id", firstCategory.getId());
						fistClassifyMap.put("name", firstCategory.getName());
						fistClassifyMap.put("icoPath", firstCategory.getIcoPath());
						fistClassifyMap.put("junior", secondClassifyList);
						// 热门品牌
						List<BrandHot> hotBrandList = this.brandHotMapper.selectHotBrandsByCateId(firstCategory.getId());
						List<Map<String, Object>> hotBrandMapList = new ArrayList<Map<String,Object>>();
						if (!CollectionUtils.isEmpty(hotBrandList)) {
							for (BrandHot hotBrand : hotBrandList) {
								Map<String, Object> hotBrandMap = new HashMap<String, Object>();
								hotBrandMap.put("id", hotBrand.getId());
								hotBrandMap.put("brand_name", hotBrand.getBrandName());
								hotBrandMap.put("logo_path", hotBrand.getLogoPath());
								hotBrandMapList.add(hotBrandMap);
							}
						}
						fistClassifyMap.put("hotBranchs", hotBrandMapList);
						goodsClassifyList.add(fistClassifyMap);
					}
				}*/
			}
		}
		return goodsClassifyList;
	}
	
	/**
	 * 根据二级分类ID查询三级分类列表
	 */
	@Override
	public List<Map<String, Object>> thirdGoodsClassifyList(int parentId) {
		List<Map<String, Object>> thirdGoodsClassifyList = new ArrayList<Map<String,Object>>();
		List<Category> thirdCategoryList = this.categoryMapper.selectThirdCategoryByParentIdAndIsShow(parentId,1);
		if (!CollectionUtils.isEmpty(thirdCategoryList)) {
			String secondCategoryIds = "";
			// 第一个为【全部】
			Map<String, Object> thirdClassifyRootMap = new HashMap<String, Object>();
			thirdClassifyRootMap.put("id", "0");
			thirdClassifyRootMap.put("name", "全部");
			thirdGoodsClassifyList.add(thirdClassifyRootMap);
			// 其他三级分类
			for (Category thirdCategory : thirdCategoryList) {
				secondCategoryIds += thirdCategory.getId() + ",";
				Map<String, Object> thirdClassifyStemMap = new HashMap<String, Object>();
				thirdClassifyStemMap.put("id", thirdCategory.getId());
				thirdClassifyStemMap.put("name", thirdCategory.getName());
				thirdGoodsClassifyList.add(thirdClassifyStemMap);
			}
			thirdClassifyRootMap.put("id", secondCategoryIds.substring(0, secondCategoryIds.length()-1));
			// 修改【全部】分类下的id值
			thirdGoodsClassifyList.set(0, thirdClassifyRootMap);
		}
		return thirdGoodsClassifyList;
	}
	
	/**
	 * 根据三级商品分类ID查询三级商品分类商品列表
	 */
	@Override
	public List<GoodsListResponse> thirdGoodsClassifyGoodsList(String categoryIds, Integer storeUserId, int startIndex, Integer pageSize) {
		List<GoodsListResponse> thirdClassifyGoodsList = new ArrayList<GoodsListResponse>();
		// 是否按照sort_no排序 0否，1是
		int isOrderBySortNo = 0;
		if (categoryIds.split(",").length > 0) {// 全部
			isOrderBySortNo = 1;
		}
		List<Goods> listGoods = this.categoryMapper.selectGoodsByCategoryIdWithPage(categoryIds,isOrderBySortNo,startIndex,pageSize);
		if (CollectionUtils.isEmpty(listGoods)) {
			return thirdClassifyGoodsList;
		}
		User user = this.userMapper.selectByPrimaryKey(Long.valueOf(storeUserId));
		List<Long> goodsIds = new ArrayList<Long>();
		for(Goods goods : listGoods){
			goodsIds.add(goods.getId());
		}
		// 价格信息集合
		Map<Long,GoodsPrice> goodsPriceMap = this.goodsService.getGoodsViewPriceForGoods(user, goodsIds);
		// 库存信息结合
		Map<Long,Long> inventoryMap = this.inventoryService.findDynaByGoodsId(goodsIds);
		// 是否上下架
		Map<Long, StoreGoods> storeGoodsMap = storeGoodsService.queryStoreGoods(Long.valueOf(storeUserId), goodsIds);
		for (Goods goods : listGoods) {
			GoodsListResponse goodsListResponse = new GoodsListResponse();
			goodsListResponse.setGoodId(goods.getId());
			goodsListResponse.setLabelName(goods.getLabelName());
			goodsListResponse.setGoodsName(goods.getName());
			goodsListResponse.setName(goods.getName());
			goodsListResponse.setSuggestedPrice(goods.getSuggestedPrice());
			/*if(!StringUtils.isBlank(goods.getGoodsWidthPic())){
				goodsListResponse.setGoodNavigateImage(goods.getGoodsWidthPic());
			}else{*/
			List<GoodsNavigate> goodsNavigateList = this.goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
			if (!CollectionUtils.isEmpty(goodsNavigateList)) {
				goodsListResponse.setGoodNavigateImage(goodsNavigateList.get(0).getNavigateImage());
			}
			/*}*/
			goodsListResponse.setBrandName("");
			goodsListResponse.setSelfSupport(goods.getSelfSupport());
			//价格信息
			GoodsPrice goodsPrice = goodsPriceMap.get(goods.getId())==null?this.goodsService.getGoodsViewPriceForGoods(user, goods.getId()):goodsPriceMap.get(goods.getId());
			String nowTime = DateUtil.currentStringDate();
			//商品标签
			List<Map<String,String>> labelArray = new ArrayList<Map<String,String>>();
			String saleStatus = "NormalSale";// 默认原价销售状态
			Long productId = goodsPrice.getProductId();
			// 查询是否存在分时抢购活动
			Map<String,Object> ltsMap = this.goodsMapper.selectNearlyLimitTimeSale(goods.getId(),productId,nowTime);
			if(ltsMap != null){
				Map<String,String> tmLabel = new HashMap<String, String>();
				// 分时抢购开始时间
				try {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date fullBeginTime = sdf.parse(ltsMap.get("fullBeginTime").toString());
					// 系统当前时间
					long nowTimeMillis = System.currentTimeMillis();
					if (fullBeginTime.getTime() > nowTimeMillis) {// 预热中
						saleStatus = "PreHeat";
						tmLabel.put("label", "预热");
					} else {// 抢购中
						saleStatus = "SecKill";
						tmLabel.put("label", "特卖");
					}
				} catch (ParseException e) {
					
				}
				tmLabel.put("color", "#ff4b7a");
				labelArray.add(tmLabel);
			}
			// 实时库存
			long realTimeInventory = inventoryMap.get(goods.getId())==null?this.inventoryService.findDynaByGoodsId(goods.getId()):inventoryMap.get(goods.getId());
			// 下架了
			if(goods.getOnlineTime() == null || 
					goods.getOfflineTime() == null || 
					(DateUtil.betweenTime(goods.getOnlineTime(), goods.getOfflineTime()) < 1)){
				saleStatus = "UnderCarriage";
			}
			// C区商品  设置为已下架状态
			if(goods.getGoodsType() == 0){
				saleStatus = "UnderCarriage";
			}
			if(goods.getSelfSupport()==0){
				Map<String,String> zyLabel = new HashMap<String, String>();
				zyLabel.put("label", "自营");
				zyLabel.put("color", "#ff4b7a");
				labelArray.add(zyLabel);
			}
			if (storeGoodsMap.get(goods.getId()) == null) {
				goodsListResponse.setUpOrDown(0);
			}else{
				goodsListResponse.setUpOrDown(1);
			}
			
			goodsListResponse.setSaleStatus(saleStatus);// 销售状态
			goodsListResponse.setGoodsPrice(goodsPrice);// 价格信息
			goodsListResponse.setInventoryNum(realTimeInventory);// 库存数
			goodsListResponse.setSalerNums(goods.getUpCount());
			goodsListResponse.setLabelArray(labelArray);// 标签信息
			thirdClassifyGoodsList.add(goodsListResponse);
		}
		// 累加店铺分享被打开次数
		return thirdClassifyGoodsList;
	}
}
